package com.xcjh.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.xcjh.domain.DataAcquisition;
import com.xcjh.dto.BaseMember;
import com.xcjh.dto.zhenai.ZhenResult;
import com.xcjh.dto.zhenai.ZhenUserDto;
import com.xcjh.eums.AppType;
import com.xcjh.opencv.ImageUtil;
import com.xcjh.service.DataAcquisitionService;
import com.xcjh.service.ZhenaiService;
import com.xcjh.utils.AssertUtils;
import com.xcjh.utils.SystemUtil;
import com.xcjh.websocket.WebSocketSever;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class ZhenaiServiceImpl implements ZhenaiService {

    @Autowired
    private DataAcquisitionService dataAcquisitionService;


    @Override
    public void save(String body) {
    }

    /**
     * 把数据存到 采集表中
     *
     * @param body
     * @return 已经存在的并且已经发送过的数据, 前端需要隐藏
     */
    @Override
    public List<String> insertData(String body) {
        //zhenai 35 yidui 35 marry 30 sjjy bh yiban 30

        ZhenResult result = JSONUtil.toBean(body, ZhenResult.class);
        if (CollectionUtil.isNotEmpty(result.getData().getList())) {
            List<DataAcquisition> collect = result.getData().getList().stream().map(this::buildData).collect(Collectors.toList());
            List<String> ids = collect.stream().map(DataAcquisition::getAppId).collect(Collectors.toList());
            //所有数据,不管发没发送过
            List<DataAcquisition> dbAll = dataAcquisitionService.lambdaQuery()
                    .in(DataAcquisition::getAppId, ids)
                    .eq(DataAcquisition::getType, AppType.ZHENAI.getMessage())
                    .list();
            //已经存在并且发送过的数据
            List<DataAcquisition> dbData = CollectionUtil.isEmpty(dbAll) ? new ArrayList<>() : dbAll.stream()
                    .filter(DataAcquisition::getSend)
                    .collect(Collectors.toList());

            //移除所有数据库已经存在过的数据,只保存新数据
            if (CollectionUtil.isNotEmpty(dbAll)) {
                collect.removeAll(collect.stream()
                        .filter(d -> dbAll.stream().anyMatch(da -> Objects.equals(da.getAppId(), d.getAppId())))
                        .collect(Collectors.toList())
                );
            }
            if (CollectionUtil.isNotEmpty(collect)) {
                dataAcquisitionService.saveBatch(collect);
            }

            //如果存在这些发送过的数据,那么就返回并且让前端隐藏
            if (CollectionUtil.isNotEmpty(dbData)) {
                return dbData.stream().map(DataAcquisition::getAppId).collect(Collectors.toList());
            }
        }
        return null;
    }

    /**
     * 传入一个文本列表,返回哪些是已经保存过的
     * @param textList
     * @return
     */
    @Override
    public List<String> check(List<String> textList){
        List<DataAcquisition> list = dataAcquisitionService.lambdaQuery()
                .in(DataAcquisition::getOther, textList)
                .eq(DataAcquisition::getSend, true)
                .list();
        addMyData(list);
        return list.stream().map(DataAcquisition::getOther).collect(Collectors.toList());
    }

    private void addMyData(List<DataAcquisition> list){
        String file="zhenaiUser.txt";
        URL resource = ImageUtil.class.getClassLoader().getResource("");
        AssertUtils.isTrue(resource!=null,"找不到路径,请检查环境.在idea下运行 不要打包");
        File classPath=new File(resource.getPath());
        String path=classPath.getParentFile().getParentFile().getAbsolutePath()+"/src/main/resources/fiddlerRule/";
        String picPath=new File(path+file).getAbsoluteFile().toString();
        List<String> users = FileUtil.readUtf8Lines(new File(path + file));
        list.addAll(users.stream().map(s->{
            DataAcquisition d=new DataAcquisition();
            d.setOther(s);
            return d;
        }).collect(Collectors.toList()));
    }

    /**
     * 发消息
     *
     * @param zhenAppId
     * @return
     */
    @Override
    public String sendApp(String zhenAppId) {
        DataAcquisition zhen = dataAcquisitionService.lambdaQuery()
                .eq(DataAcquisition::getType, AppType.ZHENAI.getMessage())
                .eq(DataAcquisition::getAppId, zhenAppId)
                .list().stream().findFirst().orElse(null);
        if (zhen != null) {
            zhen.setSend(true);
            dataAcquisitionService.lambdaUpdate()
                    .set(DataAcquisition::getSend,true)
                    .eq(DataAcquisition::getId,zhen.getId())
                    .update();
        } else {
            DataAcquisition dataAcquisition = new DataAcquisition();
            dataAcquisition.setType(AppType.ZHENAI.getMessage());
            dataAcquisition.setAppId(zhenAppId);
            dataAcquisition.setSend(false);
            dataAcquisitionService.save(dataAcquisition);
            zhen = dataAcquisition;
        }
        String msgs= buildMsg(zhen);
        BaseMember msg=new BaseMember();
        msg.setAvatar_url("");
        msg.setViewStr(msgs);
        WebSocketSever.sendMessageByUser("zhenai", JSONUtil.toJsonStr(msg));
        SystemUtil.writeC(msgs);
        return null;
    }

    @Override
    public void sendJiayuanApp(String jiaAppId) {
        DataAcquisition zhen = dataAcquisitionService.lambdaQuery()
                .eq(DataAcquisition::getType, AppType.JIAYUAN.getMessage())
                .eq(DataAcquisition::getAppId, jiaAppId)
                .list().stream().findFirst().orElse(null);
        if(zhen==null){
            DataAcquisition dataAcquisition = new DataAcquisition();
            dataAcquisition.setType(AppType.JIAYUAN.getMessage());
            dataAcquisition.setAppId(jiaAppId);
            dataAcquisition.setSend(true);
            dataAcquisitionService.save(dataAcquisition);
        }
    }



    private String getTxt(ZhenUserDto zhenUserDto){
        String s=CollectionUtil.join(zhenUserDto.getAdvantageMsgList(),"");
        return zhenUserDto.getNickname()+s;
    }

    private String buildMsg(DataAcquisition zhen) {
        String noName = "刚刚看了你的资料,觉得你是我喜欢的女生类型.交个朋友认识一下呗.我在成都上班,你在成都吗? ";
        if (StrUtil.isEmpty(zhen.getDemoJson())) {
            return noName;
        }
        ZhenUserDto zhenUserDto = JSONUtil.toBean(zhen.getDemoJson(), ZhenUserDto.class);
        String name = zhenUserDto.getTrueName();
        if (StrUtil.isEmpty(name)) {
            return noName;
        }
        name=name.replaceAll("\\*","");
        return name + "妹妹,我是红娘牵线的介绍的.她说你比较踏实,对爱情认真.我在成都上班,你在成都吗?";
    }

    private DataAcquisition buildData(ZhenUserDto zhenUserDto) {
        DataAcquisition dataAcquisition = new DataAcquisition();
        dataAcquisition.setType(AppType.ZHENAI.getMessage());
        dataAcquisition.setAppId(zhenUserDto.getObjectID() + "");
        dataAcquisition.setSend(false);
        dataAcquisition.setDemoJson(JSONUtil.toJsonStr(zhenUserDto));
        dataAcquisition.setOther(getTxt(zhenUserDto));
        return dataAcquisition;
    }
}
